#include <rtthread.h>
#include <rtdevice.h>
#include <board.h>
#include <stdio.h>
#include <string.h>
#include "trace_log.h"

static struct log_msg msg_buf[MSG_BUF_SIZE];
static volatile uint16_t msg_index = 0;

void do_trace(const char *sfile, const int line, const char *sfunc)
{
    uint16_t idx;
    rt_base_t level;
    
    if (msg_index >= MSG_BUF_SIZE) {
        return;
    }

    // level = rt_enter_critical();
    level = rt_hw_interrupt_disable();
    
    strncpy(msg_buf[msg_index].file, sfile, 32);
    msg_buf[msg_index].line = line;
    strncpy(msg_buf[msg_index].func, sfunc, 128);
    msg_buf[msg_index].var = -1;
    msg_index++;
    
    // rt_exit_critical_safe(level);
    rt_hw_interrupt_enable(level);
}

void do_trace2(const char *sfile, const int line, const char *sfunc, const int var, const char *svar)
{
    uint16_t idx;
    rt_base_t level;
    
    if (msg_index >= MSG_BUF_SIZE) {
        return;
    }

    // level = rt_enter_critical();
    level = rt_hw_interrupt_disable();
    
    strncpy(msg_buf[msg_index].file, sfile, 32);
    msg_buf[msg_index].line = line;
    strncpy(msg_buf[msg_index].func, sfunc, 128);
    msg_buf[msg_index].var = var;
    strncpy(msg_buf[msg_index].svar, svar, 64);
    msg_index++;
    
    // rt_exit_critical_safe(level);
    rt_hw_interrupt_enable(level);
}

int trace_log_dump(void)
{
    rt_thread_mdelay(TRACE_LOG_DELAY);

    rt_base_t level = rt_enter_critical();
    for (int i = 0; i < msg_index; i++) {
        if(msg_buf[i].var == -1){
            // 函数调用跟踪，固定宽度格式
            printf("%-18s:%-4d| %-38s\n", 
                      msg_buf[i].file, 
                      msg_buf[i].line, 
                      msg_buf[i].func);
        }
        else if (msg_buf[i].var == -2) {
            // 字符串跟踪 - 高亮特殊标记
            printf("%-18s:%-4d| %-38s  %23s %s\n",
                        msg_buf[i].file,
                        msg_buf[i].line,
                        msg_buf[i].func,
                        "",
                        msg_buf[i].svar);
        }
        else{
            // 变量跟踪 - 数值右对齐
            printf("%-18s:%-4d| %-38s  %11d(0x%08x) %s\n",
                msg_buf[i].file,
                msg_buf[i].line,
                msg_buf[i].func,
                msg_buf[i].var,
                msg_buf[i].var,
                msg_buf[i].svar);
        }
        
    }
    rt_exit_critical_safe(level);
    printf("msg_index=%d\n", msg_index);

    return 0;
}